package dao.impl;

import java.util.List;

import rt.AbstractDao;
import table.AdministratorTable;
import table.ClientTable;
import entity.Administrator;
import entity.Client;

public class AdministratorDao extends
		AbstractDao<AdministratorTable, Administrator> {

	public AdministratorDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Administrator newAdministrator) {
		final AdministratorTable administratorTable = deserializeFromXml();

		int count = 0;

		for (Administrator row : administratorTable.getRows()) {
			if (row.getInfoUser().getLogin()
					.equals(newAdministrator.getInfoUser().getLogin()))
				count++;
		}

		if (count == 0) {
			administratorTable.getRows().add(newAdministrator);
		}

		serializeToXml(administratorTable);
	}

	@Override
	public void update(Administrator entity) {
		final AdministratorTable administratorTable = deserializeFromXml();
		for (final Administrator row : administratorTable.getRows()) {
			if (row.getInfoUser().getLogin()
					.equals(entity.getInfoUser().getLogin())) {
				row.getInfoUser().setName(entity.getInfoUser().getName());
				row.getInfoUser().setSurname(entity.getInfoUser().getSurname());
				break;
			}
		}
		serializeToXml(administratorTable);
	}

	@Override
	public Administrator get(final String login) {
		final AdministratorTable administratorTable = deserializeFromXml();
		for (final Administrator row : administratorTable.getRows()) {
			if (row.getInfoUser().getLogin().equals(login)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Administrator> getAll() {
		final AdministratorTable administratorTable = deserializeFromXml();
		return administratorTable.getRows();
	}

	@Override
	public void delete(String login) {
		final AdministratorTable administratorTable = deserializeFromXml();
		for (final Administrator row : administratorTable.getRows()) {
			if (row.getInfoUser().getLogin().equals(login)) {
				administratorTable.getRows().remove(row);
				break;
			}
		}
		serializeToXml(administratorTable);
	}

	@Override
	protected Class<AdministratorTable> getTableClass() {
		return AdministratorTable.class;
	}

}
